package com.watermark.core.utils;

import android.content.Context;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Build;
import android.view.View;
import android.view.WindowManager;


/**
 * 屏幕相关的工具类
 */
public class ScreenUtil {
    private static Point scPoint;
    private static float density = -1;

    /**
     * 获取设备的point，封装有屏幕尺寸信息
     *
     * @return Screen x & y
     */
    public static Point getScreenPoint() {
        if (scPoint == null) {
            scPoint = new Point(0, 0);
            WindowManager wm = (WindowManager) UIKit.getContext().getSystemService(Context.WINDOW_SERVICE);
            wm.getDefaultDisplay().getSize(scPoint);
        }
        return scPoint;
    }

    public static int getScreenWidth() {
        return getScreenPoint().x;
    }

    public static int getScreenHeight() {
        return getScreenPoint().y;
    }


    /**
     * @param dp dp值
     * @return px
     */
    public static int dp2px(float dp) {
        float density = UIKit.getContext().getResources().getDisplayMetrics().density;
        return (int) (dp * density + 0.5f);
    }

    /**
     * @param px px值
     * @return dp
     */
    public static int px2dp(int px) {
        float density = UIKit.getContext().getResources().getDisplayMetrics().density;
        return (int) ((px / density + 0.5f));
    }

    /**
     * 获取指定资源id对应的尺寸
     *
     * @param resID 尺寸资源ID
     * @return 返回的单位为 px(dp * density = px)(sp * density = px)
     */
    public static float getDimensionPX(int resID) {
        // 获取某个dimen的值,如果是dp或sp的单位,将其乘以density,如果是px,则不乘 返回float
        return UIKit.getContext().getResources().getDimension(resID);
    }

    public static float getDimensionDP(int resID) {
        return UIKit.getContext().getResources().getDimension(resID) / getDensity();
    }


    public static float getDensity() {
        if (density < 0) {
            density = UIKit.getContext().getResources().getDisplayMetrics().density;
        }
        return density;
    }


    /**
     * 获取view在屏幕中的位置
     *
     * @param view view
     * @return rect
     */
    public static Rect getLocation(View view) {
        Rect rect = new Rect();
        if (Build.VERSION.SDK_INT >= 24) {
            view.getGlobalVisibleRect(rect);
            return rect;
        } else {
            int[] location = new int[2];
            view.getLocationOnScreen(location);
            rect.left = location[0];
            rect.top = location[1];
            rect.right = rect.left + view.getWidth();
            rect.bottom = rect.top + view.getHeight();
        }
        return rect;
    }

    /**
     * 检测坐标是否再rect中
     *
     * @param x    x坐标
     * @param y    y坐标
     * @param rect rect
     * @return 是否包含
     */
    public static boolean checkInRect(float x, float y, Rect rect) {
        if (null == rect) {
            return false;
        }
        return rect.left < x && x < rect.right && rect.top < y && y < rect.bottom;
    }
}
